package com.zenghm.retrofit2.adapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import retrofit2.CallAdapter;
import retrofit2.Retrofit;

/**
 * <p>2021-04-15: create by zenghm</P>
 */
public final class LiveDataCallAdapterFactory extends CallAdapter.Factory {

    public static LiveDataCallAdapterFactory create() {
        return new LiveDataCallAdapterFactory();
    }

    private LiveDataCallAdapterFactory() {
    }

    @Nullable
    @Override
    public CallAdapter<?, ?> get(
            @NonNull Type returnType,
            @NonNull Annotation[] annotations,
            @NonNull Retrofit retrofit) {
        Class<?> rawType = getRawType(returnType);
        if (rawType != LiveData.class
                && rawType != SafeLiveData.class) {
            return null;
        }
        if (!(returnType instanceof ParameterizedType)) {
            throw new IllegalStateException(
                    "LiveData return type must be parameterized as "
                            + "LiveData<Foo> or "
                            + "LiveData<? extends Foo>");
        }
        Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType);
        return new LiveDataCallAdapter<>(responseType);
    }
}
